package com.luxf.base.domainevent.utils;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import java.util.Optional;

/**
 * @author 小66
 * @create 2021-08-22 13:07
 **/
public final class SpringContextUtils implements ApplicationContextAware {
    private static volatile ApplicationContext context;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        if (context == null) {
            synchronized (SpringContextUtils.class) {
                if (context == null) {
                    SpringContextUtils.context = applicationContext;
                }
            }
        }
    }

    public static Optional<ApplicationContext> getContext() {
        return Optional.ofNullable(context);
    }

    public static <T> T getBean(Class<T> clazz) {
        ApplicationContext context = getInnerContext();
        return context.getBean(clazz);
    }

    private static ApplicationContext getInnerContext() {
        return getContext().orElseThrow(() -> new UnsupportedOperationException("please init ApplicationContext first."));
    }
}
